//
//  LSChatViewController.swift
//  niceapp-ios
//
//  Created by sujeking on 2017/8/2.
//  Copyright © 2017年 szw. All rights reserved.
//

import UIKit
import SocketRocket
import FFToast


class LSChatViewController: UIViewController {
    
    @IBOutlet weak var inputTextField: UITextField!
    @IBOutlet weak var sendBtn: UIButton!
    @IBOutlet weak var mTableView: UITableView!
    
    var msgCell: LSLeftTableViewCell!
    var rCell: LSRightTableViewCell!
    var msgs: Array<Any>!
    var util: LSUtil?
    var lssocket:SRWebSocket?
    var uname: String!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUI()
        self.msgCell = self.mTableView.dequeueReusableCell(withIdentifier: "LSLeftTableViewCell") as! LSLeftTableViewCell
        self.rCell = self.mTableView.dequeueReusableCell(withIdentifier: "LSRightTableViewCell") as! LSRightTableViewCell
        self.msgs = []
        self.util = LSUtil()
        self.util?.delegate = self
        self.uname = ud.value(forKey: "uname") as! String
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIView.animate(withDuration: 0) {
            self.navigationController?.navigationBar.alpha = 0
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        UIView.animate(withDuration: 0) {
            self.navigationController?.navigationBar.alpha = 1
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.lssocket = LSUtil.connectWebSocket(host: kChatHost, delegate: self.util)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // MARK: - Init
    
    func setUI() {
        self.sendBtn.layer.cornerRadius = CGFloat(5)
        self.sendBtn.layer.borderWidth = CGFloat(1)
        self.sendBtn.layer.borderColor = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1).cgColor
        
        self.mTableView.register(UINib.init(nibName: "LSLeftTableViewCell", bundle: nil), forCellReuseIdentifier: "LSLeftTableViewCell")
        self.mTableView.register(UINib.init(nibName: "LSRightTableViewCell", bundle: nil), forCellReuseIdentifier: "LSRightTableViewCell")
        
        let icon = UIImageView(image: #imageLiteral(resourceName: "exit"))
        icon.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(LSChatViewController.exit))
        icon.addGestureRecognizer(tap)
        
        icon.frame = CGRect(x: 0, y: 0, width: 20, height: 45/2)
        let exitBtn = UIBarButtonItem(customView: icon)
        self.navigationItem.rightBarButtonItem = exitBtn as UIBarButtonItem
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView())
        
    }
    
    // MARK: - Action
    
    func exit() {
        if self.lssocket?.readyState == SRReadyState.CLOSED {
            _ = self.navigationController?.popViewController(animated: true)
            return
        }
        
        ud.removeObject(forKey: "uname")
        ud.synchronize()
        self.lssocket?.close()
    }
    
    @IBAction func sendMsg() {
        
        if self.lssocket?.readyState == SRReadyState.CLOSED {
            let toast = FFToast.init(toastWithTitle: "提示", message: "服务器连接失败,不能发送消息", iconImage: nil) as FFToast
            toast.toastBackgroundColor = #colorLiteral(red: 0.4, green: 0.4941176471, blue: 0.9176470588, alpha: 1)
            toast.duration = 3
            toast.show()
            return
        }
        
        if self.inputTextField.text?.characters.count != 0 {
            let msgmodel = LSMsgModel()
            msgmodel.umsg = self.inputTextField.text
            msgmodel.uname = self.uname
            msgmodel.rule = true
            let json = LSUtil.conver2JSON(obj: msgmodel)
            LSUtil.sendMsg(msg: json, websocket: self.lssocket)
            self.msgs.append(msgmodel)
            self.inputTextField.text = nil;
            self.updateTableView()
            
        }
    }
    
    func updateTableView() {
        self.mTableView.reloadData()
        if self.mTableView.contentSize.height > self.mTableView.bounds.height {
            self.mTableView.scrollToBottom()
        }
    }
}



extension LSChatViewController: UITableViewDataSource,UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.msgs.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let row = indexPath.row
        let model = msgs[row] as! LSMsgModel;
        if !model.rule! {
            let cell = tableView.dequeueReusableCell(withIdentifier: "LSLeftTableViewCell", for: indexPath) as! LSLeftTableViewCell
            cell.msgLabel.text = model.umsg
            cell.unameLabel.text = model.uname
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "LSRightTableViewCell", for: indexPath) as! LSRightTableViewCell
            cell.msgLabel.text = model.umsg
            cell.unameLabel.text = model.uname
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let row = indexPath.row
        let model = msgs[row] as! LSMsgModel;
        if !model.rule! {
            self.msgCell.msgLabel.text = model.umsg
            let height = self.msgCell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height + 1
            return height
            
        } else {
            self.rCell.msgLabel.text = model.umsg
            let height = self.rCell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height + 1
            
            return height
        }
    }
}

extension LSChatViewController: UITextFieldDelegate {
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        self.updateTableView()
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.updateTableView()
    }
}

extension LSChatViewController: LSWebSocketDelegate {
    
    func webSocketDidOpen(_ webSocket: SRWebSocket!) {
        let dict = ["umsg":self.uname];
        let json = LSUtil.conver2JSON(obj: dict as AnyObject!)
        self.lssocket?.send(json)
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
        let msgModel:LSMsgModel = LSMsgModel.yy_model(withJSON: message)!
        msgModel.rule = false
        self.msgs.append(msgModel)
        self.updateTableView()
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didFailWithError error: Error!) {
        let toast = FFToast.init(toastWithTitle: "提示", message: "连接服务器失败", iconImage: nil) as FFToast
        toast.toastBackgroundColor = #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1)
        toast.duration = 3
        toast.show()
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
        _ = self.navigationController?.popViewController(animated: true)
    }
}

